package com.qf.mybatis01.service.impl;

import com.qf.mybatis01.dao.UserDao;
import com.qf.mybatis01.entity.User;
import com.qf.mybatis01.service.UserService;
import com.qf.mybatis01.utils.MyCache;
import com.qf.mybatis01.utils.MybatisUtils;

public class UserServiceImpl implements UserService {
    @Override
    public User getUser(Integer id) {

        //1. 检查缓存中是否有该id的用户数据存在
        User user = (User) MyCache.data.get(id);
        if (user != null) {  //缓存命中
            System.out.println("缓存命中id="+id);
            return user;
        }

        //2. 查询数据库
        final UserDao userDao = MybatisUtils.getMapper(UserDao.class);
        user = userDao.getUserById(2);
        if (user!=null){
            MyCache.data.put(id,user);  // 放入缓存
        }

        return user;
    }
}
